﻿using Windows7.Multitouch.Manipulation;

namespace Tanagram.Behaviors.Touch
{
    public class InertialManager
    {
        public VectorF InitialVelocity { get; set; }
        public float InitialAngularVelocity { get; set; }
        public float InitialExpansionVelocity { get; set; }
        public System.Diagnostics.Stopwatch _stopwatch = new System.Diagnostics.Stopwatch();
        public void Reset()
        {
            InitialVelocity = new VectorF(0, 0);
            InitialAngularVelocity = 0;
            InitialExpansionVelocity = 0;
            _stopwatch.Reset();
            _stopwatch.Start();
        }

        public void Stop()
        {
            _stopwatch.Stop();
        }

        //update velocities, velocity = distance/time
        public void Update(ManipulationDeltaEventArgs e, float history)
        {
            float elappsedMS = (float)_stopwatch.ElapsedMilliseconds;
            if (elappsedMS == 0)
                elappsedMS = 1;

            InitialVelocity = InitialVelocity * history + ((VectorF)e.TranslationDelta * (1F - history)) / elappsedMS;
            InitialAngularVelocity = InitialAngularVelocity * history + (e.RotationDelta * (1F - history)) / elappsedMS;
            InitialExpansionVelocity = InitialExpansionVelocity * history + (e.ExpansionDelta * (1F - history)) / elappsedMS;
            //Debug.WriteLine("1 ms:" + elappsedMS + " Velocity:" + InitialVelocity.Magnitude/elappsedMS + " Magnitude:" + InitialVelocity.Magnitude + " Angle:" + InitialAngularVelocity + " Expansion:" + InitialExpansionVelocity); 
            if (InitialVelocity.Magnitude / elappsedMS > .2F)
            {
                InitialVelocity = InitialVelocity * (.2F / InitialVelocity.Magnitude / elappsedMS);
                //Debug.WriteLine("2 ms:" + elappsedMS + " Velocity:" + InitialVelocity.Magnitude / elappsedMS + " Magnitude:" + InitialVelocity.Magnitude + " Angle:" + InitialAngularVelocity + " Expansion:" + InitialExpansionVelocity);

            }
            _stopwatch.Reset();
            _stopwatch.Start();
        }
    }
}
